# Don't forget to:
#	gem install httpclient
# TODO:
#   catch if the passfile won't open
#   die better if bad args to initialize
#   doublecheck that wavs and mp3s are grepped in taskfiles in hitapi
#   search for $ and make sure the only variables that use them are globals. no strict! blah!
#   make sure that SSL works
#   make sure that the files opened in hitapi are getting closed

require 'rubygems'
require 'digest/sha2'
# gem install httpclient
require 'httpclient'
$filelistseparator = "\t"
$errorlistseparator = ';'
$tasklistseparator = "\t"

class Phone
        def initialize(*args)
                @url = args.shift
                #puts args.public_methods
                if args.size == 2
                        @user = args.shift
                        @pass = args.shift
                        #print "user=-" + @user + "- pass=-" + @pass + "-\n"
                elsif args.size == 1
                        passfn = args.shift
                        passfile = File.open(passfn)
                        @user = passfile.readline
                        @pass = passfile.readline
                        passfile.close
                        @user.gsub!(/[\r\n]+/,"")
                        @pass.gsub!(/[\r\n]+/,"")
                        #print "user=-" + @user + "- pass=-" + @pass + "-\n"
                else
                        puts "usage: Phone.new(user, pass) or Phone.new(filename)"
                        exit 1
                end
                @hash = Digest::SHA512.hexdigest(@user + @pass)
                self.updatesalt
        end

        def updatesalt()
                @salt = rand(1000000).to_i.to_s + Time.new.to_i.to_s
                @saltyhash = Digest::SHA512.hexdigest(@salt + @hash)
        end

        def call(number, callerid, tasktype, task)
                missingfiles = []
                responsetext = self.hitapi(number, callerid, tasktype, task)

                if (responsetext =~ /^-ERRORRETRY/)
                        #responsetext.split(/#{$errorlistseparator}/).each do |errstr|
                        for errstr in responsetext.split(/#{$errorlistseparator}/)
                                errstr.gsub!(/[\r\n]+/,"")
                                if (errstr =~ /^-ERROR/)
                                        next
                                elsif (errstr =~ /^needfile - (.*)/)
                                        missingfiles.push $1
                                else
                                        return(responsetext)
                                end
                        end
                        responsetext = self.hitapi(number, callerid, tasktype, task, missingfiles.join($filelistseparator))
                end
                return(responsetext)
        end

        def hitapi(number, callerid, tasktype, task, sendfilelist="")
                sendfiles=sendfilelist.split(/#{$filelistseparator}/)
                taskfiles = task.split(/#{$tasklistseparator}/).grep(/\.wav$/ || /\.mp3$/).uniq if (tasktype == "message")

                fields = {}
                fields['version'] = 1
                fields['nums'] = number
                fields['callerid'] =callerid
                fields['task'] = task
                fields['tasktype'] = tasktype
                fields['user'] = @user
                fields['hash'] = @saltyhash
                fields['salt'] = @salt
                if (taskfiles.size > 0)
                        filenum = 0
                        for currfile in taskfiles
                                # no need for donefiles list, taskfiles is unique because of the uniq() method
                                if (File.exists?(currfile))
                                        filenum+=1
                                        fields["filesize" + filenum.to_s] = File.size(currfile)
                                        # filetime s/b seconds since 1970
                                        fields["filetime" + filenum.to_s] = File.mtime(currfile).to_i.to_s
                                        fields["file" + filenum.to_s] = currfile
                                end
                                if (sendfiles.index(currfile)) # if this file from the task was requested
                                        return ("-ERROR" + $errorlistseparator + currfile + " does not exist (client error)") if (!File.exists?(currfile))
                                        fields['fileattached' + filenum.to_s] = "T"
                                        fields["file" + filenum.to_s] = File.open(currfile,'rb')
                                end
                        end # for currfile
                        fields["filecount"] = filenum
                end # if (taskfiles.count > 0)
                browser = HTTPClient.new
                response = browser.post(@url, fields)
                if (response.status >= 200 and response.status<=299)
                        return(response.content)
                else
                        return("-ERROR" + $errorlistseparator + response.status + " " + response.reason)
                end
        end # def hitapi
end # class Phone
